<?
	$VALID_BID_LIST = array(
		'bn',		// 공지사항
		'bf',		// 자유게시판
		'bq',		// Q&A
		'pds'		// Q&A
	);

	//게시판 유효형 체크
	function TalkBoard_IsValidBid($b)
	{
		global $VALID_BID_LIST;
		if(!in_array($b, $VALID_BID_LIST))
			jserror("게시판이 존재하지 않습니다.","document.location='about:blank'");
		else
			return 1;
	}

	//게시판 이름 구하기
	function TalkBoard_GetTableName($bid)
	{
		if($bid == "bn")
			return "BRD_NOTICE";
		else
		if($bid == "bf")
			return "BRD_FREE";
		else
		if($bid == "bq")
			return "BRD_QNA";
		else
		if($bid == "pds")
			return "BRD_PDS";
	}

	function &TalkBoard_GetArticleCount($bid, $options)
	{
		$db = GetDefaultConnection();
		global $s_member_level;
		$table_name = TalkBoard_GetTableName($bid);
		$select  = " SELECT COUNT(no) AS cnt ";
		$from  = " FROM $table_name";

		if ($options['qtype'] == "name")
			$where .= " WHERE (writer_name LIKE '%" . $options['query'] . "%')";
		elseif ($options['qtype'] == "subject")
			$where .= " WHERE (subject LIKE '%" . $options['query'] . "%')";
		elseif ($options['qtype'] == "content")
			$where .= " WHERE (content LIKE '%" . $options['query'] . "%')";

		$sql = $select . $from . $where;
		$row = $db->queryRow($sql);
		return $row->getNumber("cnt");
	}

	function &TalkBoard_GetArticleList($bid, $page, $pagesize, $options)
	{
		$db = GetDefaultConnection();
		global $s_member_level;
		$table_name = TalkBoard_GetTableName($bid) ;
		$select  = " SELECT *, DATE_FORMAT(DATE_SUB(SYSDATE(), INTERVAL 24 HOUR),'%Y%m%d' ) - DATE_FORMAT(reg_date,'%Y%m%d' ) as date_diff ";
		$from  = " FROM $table_name	";

		if ($options['qtype'] == "name")
			$where .= " WHERE (writer_name LIKE '%" . $options['query'] . "%')";
		elseif ($options['qtype'] == "subject")
			$where .= " WHERE (subject LIKE '%" . $options['query'] . "%')";
		elseif ($options['qtype'] == "content")
			$where .= " WHERE (content LIKE '%" . $options['query'] . "%')";
		$orderby = " ORDER BY tid DESC, todr ASC";

		$start = ($page - 1) * $pagesize;
		$limit = " LIMIT $start, $pagesize";

		$sql = $select . $from . $where . $orderby . $limit;

		return $db->queryList($sql);
	}


	function printPageList($page, $totalpage, $pagelistsize, $urlbase, $param = null)
	{
		$totalpagelist = ceil($totalpage/$pagelistsize);
		$pagelist = ceil($page/$pagelistsize);
		if ($pagelist > $totalpagelist)
			$pagelist = $totalpagelist;
		if ($pagelist < 1)
			$pagelist = 1;

		$startpagelist = ($pagelist - 1) * $pagelistsize + 1;
		$endpagelist = $startpagelist + $pagelistsize - 1;
		if ($endpagelist > $totalpage)
			$endpagelist = $totalpage;
		if ($endpagelist < 1)
			$endpagelist = 1;
		unset($param['page']);
		$parambase = encodeParamArray($param);

		if (strstr($urlbase, '?'))
			$urlbase .= '&';
		else
			$urlbase .= '?';

		if ($parambase)
			$urlbase .= $parambase . "&";
	/*
	                <a href="#" class="direction prev"><span></span><span></span> 처음</a>
	                <a href="#" class="direction prev"><span></span> 이전</a>
	                <a href="#">1</a>
	                <a href="#">2</a>
	                <a href="#">3</a>
	                <a href="#">4</a>
	                <strong>5</strong>
	                <a href="#">6</a>
	                <a href="#">7</a>
	                <a href="#">8</a>
	                <a href="#">9</a>
	                <a href="#" class="direction next">다음 <span></span></a>
	                <a href="#" class="direction next">끝 <span></span><span></span></a>
	*/

		echo "<a href='" . $urlbase . "page=1' class='direction prev'><span></span><span></span> 처음</a>";
		if ($startpagelist > 1)
		{
			echo "<a href='" . $urlbase . "page=" . ($startpagelist-1) . "' class='direction prev'><span></span> 이전</a>";
		}
		else
		{
			echo "<a href='" . $urlbase . "page=1' class='direction prev'><span></span> 이전</a>";
		}

		for ($i = $startpagelist; $i <= $endpagelist; $i++)
		{
			if ($i == $page)
				echo "<strong>$i</strong>";
			else
				echo "<a href='" . $urlbase . "page=" . $i . "'>" . $i . "</a>";
		}

		if ($endpagelist < $totalpage)
		{
			echo "<a href='" . $urlbase . "page=" . ($endpagelist + 1) . "' class='direction next'>다음 <span></span></a>";
		}
		else
		{
			echo "<a href='" . $urlbase . "page=" . $totalpage . "' class='direction next'>다음 <span></span></a>";
		}
		echo "<a href='" . $urlbase . "page=" . $totalpage . "' class='direction next'>끝 <span></span><span></span></a>";
	}

	function SaveFile($origin, $dir_name, $file_name)
	{
		if (!file_exists($dir_name))
		{
			$rs = mkdir($dir_name, 0757); //0707, 0757
			if (!$rs)
				return false;
			$rs = copy($origin, "$dir_name/$file_name");
			if (!$rs)
				return false;
		}
		elseif (!is_dir($dir_name) || !is_writable($dir_name))
		{
			return false;
		}
		else
		{
			$rs = copy($origin, "$dir_name/$file_name");
			if (!$rs)
				return false;
		}
		return true;
	}

	function RemoveDirFiles($dir, $DeleteMe) {
	    if(!$dh = @opendir($dir)) return;
	    while (false !== ($obj = readdir($dh))) {
	        if($obj=='.' || $obj=='..') continue;
	        if (!@unlink($dir.'/'.$obj)) RemoveDirFiles($dir.'/'.$obj, true);
	    }
	    closedir($dh);
	    if ($DeleteMe){
	        @rmdir($dir);
	    }
	}

	function TalkBoard_InsertArticle($bid, $array)
	{
		$db = GetDefaultConnection();
		$table_name = TalkBoard_GetTableName($bid);

		$sql = "SELECT MAX(tid) AS maxtid FROM $table_name";
		$row =& $db->queryRow($sql);
		$tid = $row->getNumber('maxtid') + 1;

		$now = date('Y-m-d H:i:s');
		$array['tid']			= $tid;
		$array['todr']			= 0;
		$array['tdpt']			= 0;
		$array['reg_date']	= $now;

		$result = $db->queryInsert($table_name, $array);
		$no = mysql_insert_id();

		if (!$result)
			return -1;
		else
			return $no;
	}

	function TalkBoard_ReplyArticle($ono, $bid, &$array)
	{
		$db = GetDefaultConnection();
		$table_name = TalkBoard_GetTableName($bid);

		$db->begin();

		$sql = "SELECT tid AS o_tid, todr AS o_todr, tdpt AS o_tdpt FROM $table_name WHERE no = '$ono'";
		$row =& $db->queryRow($sql);
		$o_tid = $row->getNumber('o_tid');
		$o_todr = $row->getNumber('o_todr');
		$o_tdpt = $row->getNumber('o_tdpt');

		$sql  = "UPDATE $table_name SET todr = todr + 1";
		$sql .= " WHERE tid = '$o_tid' AND todr > '$o_todr'";
		$result = $db->query($sql);
		if (!$result)
		{
			$db->rollback();
			return -1;
		}

		$now = date('Y-m-d H:i:s');
		$array['tid']			= $o_tid;
		$array['todr']			= $o_todr + 1;
		$array['tdpt']			= $o_tdpt + 1;
		$array['reg_date']	= $now;

		$result = $db->queryInsert($table_name, $array);
		$no = mysql_insert_id();
		if (!$result)
		{
			$db->rollback();
			return -1;
		}
		$db->commit();
		return $no;
	}

	function TalkBoard_UpdateArticle($bid, $no, &$array)
	{
		$db = GetDefaultConnection();
		$table_name = TalkBoard_GetTableName($bid);
		return $db->queryUpdate($table_name, $array, " (no = '$no')");
	}


	/*
	// 삭제 처리 로직
	if (답변글존재) {
		UPDATE delete_flag;
	} else {
		DELETE;
		UPDATE todr;
	}
*/
function  TalkBoard_DeleteArticle($bid, $no, $tid, $todr, $tdpt, $delete_message = null)
{
	$db = GetDefaultConnection();
	$table_name = TalkBoard_GetTableName($bid);

	$db->begin();

	// 답변이 존재하는지 검사
	$sql = "SELECT COUNT(no) AS has_child FROM $table_name";
	$sql .= " WHERE tid = '$tid' AND todr = '" . ($todr + 1) . "' AND tdpt > '$tdpt'";
	$row =& $db->queryRow($sql);
	$has_child = $row->getNumber('has_child');

	if ($has_child)
	{
		// 답변이 존재함 delete_flag만 업데이트

		//$now = date('Y-m-d H:i:s');
		if (!$delete_message)
			$delete_message = "(삭제되었습니다.)";
		$array = array(
			'delete_flag'		=> 1,
			'subject'			=> $delete_message,
			'content'			=> $delete_message,
		);

		$result = $db->queryUpdate($table_name, $array, " (no = '$no')");
		if (!$result)
		{
			$db->rollback();
			return false;
		}
	}
	else
	{
		// 답변이 존재하지 않음. 실제 삭제 수행
		$result = $db->queryDelete($table_name, " (no = '$no')");
		if (!$result)
		{
			$db->rollback();
			return false;
		}

		// 쓰레드 순서를 재조정
		$sql  = "UPDATE $table_name SET todr = todr - 1";
		$sql .= " WHERE tid = '$tid' AND todr > '$todr'";
		$result = $db->query($sql);
		if (!$result)
		{
			$db->rollback();
			return false;
		}
	}

	$db->commit();
	return true;
}

function TalkBoard_IncreseHitcount($bid, $no)
{
	$db = GetDefaultConnection();
	$table_name = TalkBoard_GetTableName($bid) ;
	$sql = "UPDATE $table_name SET hit_count = hit_count + 1 WHERE no = '$no'";
	return $db->query($sql);
}


function &TalkBoard_GetArticle($bid, $no)
{
	$db = GetDefaultConnection();

	$table_name = TalkBoard_GetTableName($bid);
	$select  = " SELECT * ";
	$from  = " FROM $table_name";

	$where .= " WHERE (no = '$no')";

	$sql = $select . $from . $where;

	$row =& $db->queryRow($sql);
	return $row;
}

function &Index_GetSubStr($str,$max){
	if(strlen($str) > $max){
		$str = substr($str,0,$max) . "..";
	}
	return $str;
}

//bbs path일때 board class 정의
$Is_BBS = strrpos($_SERVER['SCRIPT_NAME'], $BBS_PATH);
if ( $Is_BBS == 0 ) {
	if($b == "bn") {
		$subtt_class = "subtt10";
		$bbs_name = "공지사항";
	}
	else
	if($b == "bf") {
		$subtt_class = "subtt11";
		$bbs_name = "자유게시판";
	}
	else
	if($b == "bq") {
		$subtt_class = "subtt12";
		$bbs_name = "Q&A";
	}
	else
	if($b == "pds") {
		$subtt_class = "subtt22";
		$bbs_name = "자료실";
	}
}

//login check
require_once "_CheckLogin.php";
?>